package com.mages.debris.util;


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class CommonUtil {
    public static String MetaData(String dataURL, String auth) {
        // 元数据获取
        // 从dataURL中解析metadataURL
        String metaURL = dataURL.replaceAll("GetCoverage", "DescribeCoverage").replaceAll("&format=image/tiff", "");
        try {
            // http connection
            URL url = new URL(metaURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(6000);
            conn.setReadTimeout(6000);
            // 添加授权验证
            // String auth = Base64.getEncoder().encodeToString(String.format("%s:%s", user, password).getBytes(StandardCharsets.UTF_8));
            conn.setRequestProperty("Authorization", String.format("Basic %s", auth));
            int code = conn.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                System.out.println(conn.getErrorStream().read());
                throw new Exception("资源访问失败！");
            }
            // parse XML
            DataInputStream in = new DataInputStream(conn.getInputStream());
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(in);
            Element root = document.getRootElement();
//            Element coverageDescription = root.element("wcs:CoverageDescriptions");
            List cds = root.elements("CoverageDescription");
            if (!cds.isEmpty()) {
                Element cd = (Element) cds.get(0);
                String name = cd.elementText("name");
                Element bboxEnvelope = cd.element("boundedBy").element("Envelope");
                String bboxStr = String.format("[[%s],[%s]]", bboxEnvelope.elementText("lowerCorner").replaceAll(" ", ","), bboxEnvelope.elementText("upperCorner").replaceAll(" ", ","));
                String coverageId = cd.elementText("CoverageId");
                Element gridEnvelope = cd.element("domainSet").element("RectifiedGrid").element("limits").element("GridEnvelope");
                String higherPoint = gridEnvelope.elementText("high");
                String lowerPoint = gridEnvelope.elementText("low");
                int width = Integer.parseInt(higherPoint.split(" ")[0]) - Integer.parseInt(lowerPoint.split(" ")[0]);
                int height = Integer.parseInt(higherPoint.split(" ")[1]) - Integer.parseInt(lowerPoint.split(" ")[1]);
                String format = cd.element("ServiceParameters").elementText("nativeFormat");
                return String.format("{\"name\":\"%s\",\"coverageId\":\"%s\",\"bbox\":%s,\"height\":%d,\"width\":%d,\"format\":\"%s\"}", name, coverageId, bboxStr, height, width, format);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean ReplaceLogByUUID(String logPath, String UUID, String logLine) {
        // 更新日志状态
        File file = new File(logPath);
        if (!file.exists()) {
            return false;
        } else {
            try {
                BufferedReader in = new BufferedReader(new FileReader(file));
                List<String> lines = new ArrayList<>();
                String line;
                while ((line = in.readLine()) != null) {
                    if (line.contains(UUID)) {
                        lines.add(logLine);
                        break;
                    } else {
                        lines.add(line + "\n");
                    }
                }
                while ((line = in.readLine()) != null) {
                    lines.add(line + "\n");
                }
                in.close();
                FileOutputStream out = new FileOutputStream(logPath);
                for (String l :
                        lines) {
                    out.write(l.getBytes(StandardCharsets.UTF_8));
                }
                out.flush();
                out.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }

}
